package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(WmUserDTO dto) {
        // 1.参数校验
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不存在");
        }
        // 2.根据用户名去数据库查找自媒体用户
        WmUser wmUser = this.getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "请先注册账户");
        }
        String salt = wmUser.getSalt();
        String password = wmUser.getPassword();

        if (!password.equals(DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes()))) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 3.判断用户当前状态是否可用
        if (wmUser.getStatus() != 9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //返回JWT结果
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        Map map = new HashMap();
        map.put("token", token);
        WmUserVO vo = new WmUserVO();
        BeanUtils.copyProperties(wmUser, vo);
        map.put("user", vo);
        return ResponseResult.okResult(map);
    }
}
